package app

import (
	"com.codingq92/go-chat/app/req"
	"com.codingq92/go-chat/app/resp"
	"com.codingq92/go-chat/global"
	"com.codingq92/go-chat/services"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

// Login 登录接口
func Login(c *gin.Context) {
	var form u_api.UserRequest
	if err := c.ShouldBindJSON(&form); err != nil {
		global.Log.Error("Login error ")
		return
	}
	if err, user := u_api.Login(form); err != nil {
		resp.BusinessFail(c, err.Error())
	} else {
		tokenData, err, _ := services.JwtService.CreateToken(services.AppGuardName, user)
		if err != nil {
			resp.BusinessFail(c, err.Error())
			return
		}
		resp.Success(c, tokenData)
	}
}

// Register 注册接口
func Register(c *gin.Context) {
	var form u_api.UserRequest
	if err := c.ShouldBindJSON(&form); err != nil {
		global.Log.Error("Register error ")
		return
	}
	if err := u_api.Register(form); err != nil {
		resp.BusinessFail(c, err.Error())
	} else {
		resp.Success(c, "注册成功")
	}
}

// UserInfo 获取用户信息
func UserInfo(c *gin.Context) {
	err, user := u_api.GetUserInfo(c.Keys["id"].(string))
	if err != nil {
		resp.BusinessFail(c, err.Error())
		return
	}
	resp.Success(c, user)
}

// Logout 登出
// 就是加入黑名单 & 设置失效时间 ： 如果没有设置失效时间，会导致黑名单巨大问题!!!
func Logout(c *gin.Context) {
	err := services.JwtService.JoinBlackList(c.Keys["token"].(*jwt.Token))
	if err != nil {
		resp.BusinessFail(c, "登出失败")
		return
	}
	resp.Success(c, nil)
}
